package com.xxwu.mybatis.mapper;
import java.util.List;
import com.xxwu.mybatis.model.userInfo;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserInfoMapper {
    //当数据库字段与Java中对象名名称不一致时，则无法进行赋值，不一致的字段查询出的结果会为null，以下通过三种方式完成正确映射
    //1 该别名
    @Select("select id, username, password, age, gender, phone," +
            " delete_flag as deleteFlag, create_time as createTime, update_time as updateTime from userinfo")
    List<userInfo> queryAllUser();

    //2 结果映射
    //单个参数名称可以不对应
    @Results(id = "BaseResult", value = {   //id不可以重复
            @Result(column = "delete_flag", property = "deleteFlag"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime")
    })
    @Select("select * from userinfo where id = #{id}")
    userInfo queryUserById(Integer userId);

    //结果映射的复用
    @ResultMap(value = "BaseResult")    //这里的value与Results中的id对应
    //多个参数名称必须对应，或者用Param注解进行重命名，但重命名后原来的名称将无法使用
    @Select("select * from userinfo where id = #{id} and age = #{age}")
    userInfo queryUserByIdAndAge(@Param("id") Integer userId, Integer age);

    //3 配置自动驼峰转换
    /*
    增删改查
     */
    //想要拿到自增的id属性，需要加上Option注解，并告知程序自增变量是赋值给id
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into userinfo(username, age, gender, phone, password) values " +
            "(#{UserInfo.username}, #{UserInfo.age}, #{UserInfo.gender}, #{UserInfo.phone}, #{UserInfo.password})")
    //当对参数进行重命名时，插入的参数就必须写为 对象.xxx 否则将会匹配失败
    Integer insertUserInfo(@Param("UserInfo") userInfo userInfo);

    @Delete("delete from userinfo where id = #{id}")
    Integer deleteUserById(Integer id);

    //这里可传对象也可传对象
    @Update("update userinfo set username = #{UserInfo.username}, password = #{UserInfo.password} " +
            "where id = #{UserInfo.id}")
    Integer updateUserInfo(@Param("UserInfo") userInfo userInfo);
}
